<?php



namespace App\Http\Controllers\Backend;

use App\Http\Requests\Company\CategoryRequest;
use App\Services\Business\Models\MediaCategory;
use App\Services\Business\Interfaces\MediaCategoryServiceInterface;
use App\Services\Business\Services\MediaCategoryService;


class MediaCategoryController extends BaseController
{
    /**
     * @var MediaCategoryService
     */
    protected $mediaCategoryService;

    public function __construct(MediaCategoryServiceInterface $mediaCategoryService)
    {
        $this->mediaCategoryService = $mediaCategoryService;
    }

    public function tree()
    {
        $companyId =$this->loginCompanyId();
        $categories = $this->mediaCategoryService->tree($companyId);
        return  $this->successData(compact('categories'));
    }

    public function store(CategoryRequest $request, MediaCategory $category)
    {
        $category->fill($request->filldata())->save();
        return $this->success(__('插入分类成功'));

    }


    public function edit($id)
    {
        $category = MediaCategory::query()->where('id', $id)->firstOrFail();

        return $this->successData($category);
    }

    public function update(CategoryRequest $request, $id)
    {
        try {
            $category = MediaCategory::query()->where('id', $id)->firstOrFail();
            $category->fill($request->filldata())->save();
            return $this->success(__('更新分类名成功'));
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function delete($id)
    {
        if (MediaCategory::query()->where('parent_id', $id)->exists()) {
            return $this->error('该分类下存在子分类，无法删除');
        }
        MediaCategory::destroy($id);
        return $this->success();
    }


}
